package com.rdtravel.services;

import com.rdtravel.entities.Booking;
import com.rdtravel.entities.Parameters;
import com.rdtravel.exceptions.AnotherCustomerBookedTheSameTripAtTheSameMomentException;
import com.rdtravel.exceptions.InvalidEntityException;

import javax.persistence.OptimisticLockException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
class JPABookingsService extends JPAService implements BookingsService {

	@Override
	public void create(Booking booking) {
		if (! validator.validate(booking).isEmpty()) {
			throw new InvalidEntityException();
		}	
		try {
			booking.getTrip().bookSeats(booking);
			entityManager.persist(booking); // JPA valideert validation
											// annotations nog een keer
		} catch (OptimisticLockException ex) {
			throw new AnotherCustomerBookedTheSameTripAtTheSameMomentException();
		} 
	}

	@Override
	public void setPriceAndDiscounts(Booking booking) {
		Parameters parameters = findParameters();
		booking.setGrossPricePerPerson(booking.getTrip()
				.getGrossPricePerPerson());
		booking.setCreditcardDiscountPercentage(parameters
				.getCreditcardDiscountPercentage());
	}

	@Override
	public Booking findById(long id) {
		return entityManager.find(Booking.class, id);
	}
}
